<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Dialogs in PyQt4</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PyQt, PyQt4, Dialogs, tutorial, Python, Linux">
<meta name="description" content="In this part of the PyQt4 tutorial, we worked
with dialogs.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Dialogs in PyQt4</h1>

<p>
Dialog windows or dialogs are an indispensable part of most modern GUI applications.
A dialog is defined as a conversation between two or more persons. In a computer 
application a dialog is a window which is used to "talk" to the application. 
A dialog is used to input data, modify data, change the application settings etc.
Dialogs are important means of communication between a user and a computer program.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 


<h2>QtGui.QInputDialog</h2>

<p>
The <code>QtGui.QInputDialog</code>  provides a simple convenience dialog to 
get a single value from the user.
The input value can be a string, a number or an item from a list. 
</p>


<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

In this example, we receive data from
a QtGui.QInputDialog dialog. 

author: Jan Bodnar
website: zetcode.com 
last edited: October 2011
"""

import sys
from PyQt4 import QtGui


class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.btn = QtGui.QPushButton('Dialog', self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showDialog)
        
        self.le = QtGui.QLineEdit(self)
        self.le.move(130, 22)
        
        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Input dialog')
        self.show()
        
    def showDialog(self):
        
        text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 
            'Enter your name:')
        
        if ok:
            self.le.setText(str(text))
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
The example has a button and a line edit widget. The button shows the 
input dialog for getting text values. 
The entered text will be displayed in the line edit widget.
</p>


<pre class="explanation">
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 
    'Enter your name:')
</pre>

<p>
This line displays the input dialog. The first string is a dialog title, 
the second one is a message within the dialog.
The dialog returns the entered text and a boolean value. If we clicked ok 
button, the boolean value is true, otherwise false.
</p>

<pre class="explanation">
if ok:
    self.le.setText(str(text))
</pre>

<p>
The text that we have received from the dialog is set to the
line edit widget. 
</p>

<br>
<img src="/img/gui/pyqt4/inputdialog.png" alt="Input Dialog">
<div class="figure">Figure: Input Dialog</div>


<h2>QtGui.QColorDialog</h2>

<p>
The <code>QtGui.QColorDialog</code> provides a dialog widget for selecting color
values. 
</p>


<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

In this example, we select a color value
from the QtGui.QColorDialog and change the background
color of a QtGui.QFrame widget. 

author: Jan Bodnar
website: zetcode.com 
last edited: October 2011
"""

import sys
from PyQt4 import QtGui

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        col = QtGui.QColor(0, 0, 0) 

        self.btn = QtGui.QPushButton('Dialog', self)
        self.btn.move(20, 20)

        self.btn.clicked.connect(self.showDialog)

        self.frm = QtGui.QFrame(self)
        self.frm.setStyleSheet("QWidget { background-color: %s }" 
            % col.name())
        self.frm.setGeometry(130, 22, 100, 100)            
        
        self.setGeometry(300, 300, 250, 180)
        self.setWindowTitle('Color dialog')
        self.show()
        
    def showDialog(self):
      
        col = QtGui.QColorDialog.getColor()

        if col.isValid():
            self.frm.setStyleSheet("QWidget { background-color: %s }"
                % col.name())
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
The application example shows a push button and a <code>QtGui.QFrame</code>. 
The widget background is set to black color. 
Using the <code>QtGui.QColorDialog</code>, we can change its background.
</p>

<pre class="explanation">
col = QtGui.QColor(0, 0, 0) 
</pre>

<p>
This is an initial color of the <code>QtGui.QFrame</code> background. 
</p>

<pre class="explanation">
col = QtGui.QColorDialog.getColor()
</pre>

<p>
This line will pop up the <code>QtGui.QColorDialog</code>.
</p>

<pre class="explanation">
if col.isValid():
    self.frm.setStyleSheet("QWidget { background-color: %s }"
        % col.name())
</pre>

<p>
We check if the color is valid. If we click on the cancel button, 
no valid color is returned. If the color is valid, we change 
the background color using stylesheets.
</p>

<br>
<img src="/img/gui/pyqt4/colordialog.png" alt="Color dialog">
<div class="figure">Figure: Color dialog</div>


<h2>QtGui.QFontDialog</h2>


<p>
The <code>QtGui.QFontDialog</code> is a dialog widget for selecting font.
</p>


<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

In this example, we select a font name
and change the font of a label. 

author: Jan Bodnar
website: zetcode.com 
last edited: October 2011
"""

import sys
from PyQt4 import QtGui


class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        vbox = QtGui.QVBoxLayout()

        btn = QtGui.QPushButton('Dialog', self)
        btn.setSizePolicy(QtGui.QSizePolicy.Fixed,
            QtGui.QSizePolicy.Fixed)
        
        btn.move(20, 20)

        vbox.addWidget(btn)

        btn.clicked.connect(self.showDialog)
        
        self.lbl = QtGui.QLabel('Knowledge only matters', self)
        self.lbl.move(130, 20)

        vbox.addWidget(self.lbl)
        self.setLayout(vbox)          
        
        self.setGeometry(300, 300, 250, 180)
        self.setWindowTitle('Font dialog')
        self.show()
        
    def showDialog(self):

        font, ok = QtGui.QFontDialog.getFont()
        if ok:
            self.lbl.setFont(font)
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>


<p>
In our example, we have a button and a label. With <code>QtGui.QFontDialog</code>, 
we change the font of the label.
</p>

<pre class="explanation">
font, ok = QtGui.QFontDialog.getFont()
</pre> 
 
<p> 
Here we pop up the font dialog. The <code>getFont()</code> method returns the
font name and the ok parameter. It is equal to True if the user clicked OK; otherwise
it is False. 
</p> 
 
<pre class="explanation">
if ok:
    self.label.setFont(font)
</pre> 
 
<p> 
If we clicked ok, the font of the label would be changed.
</p>



<h2>QtGui.QFileDialog</h2>

<p>
The <code>QtGui.QFileDialog</code> is a dialog that allows users to 
select files or directories. The files can be selected for both
opening and saving.
</p>


<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

In this example, we select a file with a
QtGui.QFileDialog and display its contents
in a QtGui.QTextEdit.

author: Jan Bodnar
website: zetcode.com 
last edited: October 2011
"""

import sys
from PyQt4 import QtGui


class Example(QtGui.QMainWindow):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.statusBar()

        openFile = QtGui.QAction(QtGui.QIcon('open.png'), 'Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&amp;File')
        fileMenu.addAction(openFile)       
        
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('File dialog')
        self.show()
        
    def showDialog(self):

        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 
                '/home')
        
        f = open(fname, 'r')
        
        with f:        
            data = f.read()
            self.textEdit.setText(data) 
                                
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

</pre>


<p>
The example shows a menubar, centrally set text edit widget and a statusbar.
The menu item shows the <code>QtGui.QFileDialog</code> 
which is used to select a file. The contents of the file are loaded 
into the text edit widget.
</p>

<pre class="explanation">
class Example(QtGui.QMainWindow):
    
    def __init__(self):
        super(Example, self).__init__()
</pre>

<p>
The example is based on the <code>QtGui.QMainWindow</code> widget, 
because we centrally set the text edit widget. 
</p>

<pre class="explanation">
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 
        '/home')
</pre>

<p>
We pop up the <code>QtGui.QFileDialog</code>. The first string in the 
<code>getOpenFileName()</code> method is the caption. The second string 
specifies the dialog working directory. 
By default, the file filter is set to All files (*). 
</p>

<pre class="explanation">
f = open(fname, 'r')

with f:        
    data = f.read()
    self.textEdit.setText(data) 
</pre>

<p>
The selected file name is read and the contents of the file are 
set to the text edit widget. 
</p>


<br>
<img src="/img/gui/pyqt4/filedialog.png" alt="File Dialog">
<div class="figure">Figure: File dialog</div>

<hr class="btm">

<p>
In this part of the PyQt4 tutorial, we worked with dialogs. 
</p>

<br> 
<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 9, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
